package com.innovation.ic.sc.base.service.sc.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.innovation.ic.sc.base.mapper.sc.PersonnelManagementMapper;
import com.innovation.ic.sc.base.model.sc.PersonnelManagement;

import com.innovation.ic.sc.base.pojo.enums.RedisKeyPrefixEnum;
import com.innovation.ic.sc.base.pojo.variable.ServiceResult;
import com.innovation.ic.sc.base.service.ServiceHelper;
import com.innovation.ic.sc.base.service.sc.PersonnelManagementService;
import com.innovation.ic.sc.base.vo.ManagementIdVo;
import com.innovation.ic.sc.base.vo.PersonnelManagementVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class PersonnelManagementServiceImpl extends ServiceImpl<PersonnelManagementMapper, PersonnelManagement> implements PersonnelManagementService {
    private static final Logger log = LoggerFactory.getLogger(PersonnelManagementServiceImpl.class);

    @Resource
    private ServiceHelper serviceHelper;

    /**
     * 当前主账号下关联的人员
     *
     * @return 返回当前主账号下关联的人员信息
     */
    public ServiceResult<List> findUserId(String userId) {
        ServiceResult<List> listServiceResult = new ServiceResult<>();
        Object PersonnelManagementData = serviceHelper.getRedisManager().get(RedisKeyPrefixEnum.PERSONNEL_MANAGEMENT_DATA.getCode() + "_" + userId);
        if (PersonnelManagementData == null) {
            listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            listServiceResult.setSuccess(Boolean.TRUE);
        }
        JSONArray objects = JSONArray.parseArray(String.valueOf(PersonnelManagementData));
        listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        listServiceResult.setSuccess(Boolean.TRUE);
        listServiceResult.setResult(objects);
        return listServiceResult;
    }

    /**
     * 批量更新当前主账号下关联的人员
     *
     * @return
     */
    public void updateManagedUserIds(PersonnelManagementVo personnelManagementVo) {
        ArrayList<PersonnelManagement> personnelManagements = new ArrayList<>();
        //先进行删除 当前账号下的所有人员管理信息
        String userId = personnelManagementVo.getUserId();
        QueryWrapper<PersonnelManagement> personnelManagementQueryWrapper = new QueryWrapper<>();
        personnelManagementQueryWrapper.eq("user_id", userId);
        serviceHelper.getPersonnelManagementMapper().delete(personnelManagementQueryWrapper);
        //被管理
        List<ManagementIdVo> managedUserIds = personnelManagementVo.getManagedUserIds();
        for (ManagementIdVo managedUserId : managedUserIds) {
            PersonnelManagement personnelManagement = new PersonnelManagement();
            personnelManagement.setUserId(userId);
            //被管理id
            String managedUserId1 = managedUserId.getManagedUserId();
            personnelManagement.setManagedUserId(managedUserId1);
            personnelManagements.add(personnelManagement);
        }
        //批量添加
        serviceHelper.getPersonnelManagementMapper().insertBatchSomeColumn(personnelManagements);
    }

    /**
     * 初始化优势型号数据
     */
    @Override
    public void initPersonnelManagementData() {
        // 删除redis中的优势型号数据
        Boolean deleteResult = serviceHelper.getRedisManager().delRedisDataByKeyPrefix(RedisKeyPrefixEnum.PERSONNEL_MANAGEMENT_DATA.getCode() + "*");
        if (deleteResult) {
            log.info("删除[{}]开头的数据成功", RedisKeyPrefixEnum.PERSONNEL_MANAGEMENT_DATA.getCode());
        }

        // 获取人员管理的所有数据
        List<PersonnelManagement> personnelManagementList = serviceHelper.getPersonnelManagementMapper().selectList(null);
        if (personnelManagementList != null && personnelManagementList.size() > 0) {
            Map<String, List<PersonnelManagement>> map = personnelManagementList.stream().collect(Collectors.groupingBy(PersonnelManagement::getUserId));//进行分组 按照userid
            for (String key : map.keySet()) {
                List<PersonnelManagement> personnelManagementList1 = map.get(key);
                String redisKey = RedisKeyPrefixEnum.PERSONNEL_MANAGEMENT_DATA.getCode() + "_" + key;
                String apiResultJson = JSONObject.toJSONString(personnelManagementList1, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                serviceHelper.getRedisManager().set(redisKey, apiResultJson);
            }
            log.info("导入[{}]开头的数据成功", RedisKeyPrefixEnum.PERSONNEL_MANAGEMENT_DATA.getCode());
        }

//    /**
//     * 批量删除当前主账号下关联的人员
//     *
//     * @return
//     */
//    public void deleteManagedUserIds(PersonnelManagementVo personnelManagementVo) {
//        ArrayList<Integer> idlist = new ArrayList<>();
//        List<ManagementIdVo> ids = personnelManagementVo.getIds();
//        for (ManagementIdVo id : ids) {
//            Integer idData = id.getId();
//            idlist.add(idData);
//        }
//        personnelManagementMapper.deleteBatchIds(idlist);
//    }
    }
}
